package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.qrcode.utils.CodeUtils;
import com.eightbears.beboy.entity.SuccessEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_USERCREATE_RELATION;


/**
 * 推广页面=邀请好友页面
 */
public class InviteFriendsActivity extends BaseActivity {
    private static final long DELAY_TIME = 5000;
    @BindView(R.id.ll_back)
    LinearLayout mLlBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.rl_title_root)
    RelativeLayout mRlTitleRoot;
    @BindView(R.id.tv_right_img_btn)
    TextView mTvRightImgBtn;
    @BindView(R.id.tv_save_address)
    TextView mTvSaveAddress;
    @BindView(R.id.tv_submit)
    TextView mTvSubmit;
    @BindView(R.id.iv_right_icon)
    ImageView mIvRightIcon;
    @BindView(R.id.ll_right)
    LinearLayout mLlRight;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.tv_invitefriend_text)
    TextView mTvInvitefriendText;
    @BindView(R.id.et_invitefriend_number)
    EditText mEtInvitefriendNumber;
    @BindView(R.id.tv_invitefriend_code)
    TextView mTvInvitefriendCode;
    @BindView(R.id.rl_invitefriend_number)
    RelativeLayout mRlInvitefriendNumber;
    @BindView(R.id.tv_invitefriend_verification)
    TextView mTvInvitefriendVerification;
    @BindView(R.id.et_invitefriend_verification)
    EditText mEtInvitefriendVerification;
    @BindView(R.id.rl_invitefriend_verification)
    RelativeLayout mRlInvitefriendVerification;
    @BindView(R.id.btn_invitefriend_ensure)
    Button mBtnInvitefriendEnsure;
    @BindView(R.id.ll_invitefriend_tome)
    RelativeLayout mLlInvitefriendTome;
    @BindView(R.id.iv_invite_qc)
    ImageView mIvInviteQc;
    @BindView(R.id.activity_invite_friends)
    LinearLayout mActivityInviteFriends;
    @BindView(R.id.sw_shopdetail)
    SwipeBackLayout mSwShopdetail;

    private String Qc_Url = "http://beboy.me/invite?invite_id={+" + SPUtil.getUser().getData().getUser_id() + "+} ";

    private String mInvitefriend_phone_number;

//    private ShopRelativeParentAdapter mShopRelativeAdapterParent;
//    private ShopRelativeChildrenAdapter mShopRelativeChildrenAdapter;

    //使用handler主线程刷新UI
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
//                    getData();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_friends);
        ButterKnife.bind(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        mTvTitle.setText(R.string.text_generalize);
        Bitmap image = CodeUtils.createImage(Qc_Url, 125, 125, null);
        mIvInviteQc.setImageBitmap(image);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        mSwShopdetail.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_invitefriend_ensure)
    void ensure() {
        btnEnsure();
    }


    @OnClick(R.id.tv_invitefriend_code)
    void code() {
        getPhoneVerificationCode();
    }

    @OnClick(R.id.iv_share)
    void share() {
//        SharesUtil.shareContent(mContext, post.getId());
    }

    private void getPhoneVerificationCode() {
        //获取手机号码
        mInvitefriend_phone_number = mEtInvitefriendNumber.getText().toString().trim();
        if (TextUtils.isEmpty(mInvitefriend_phone_number)) { //如果没手机号码
            ShowToast.showShortToast(getString(R.string.text_invite_set_phone_num));
            return;
        } else if (mInvitefriend_phone_number.trim().length() < 11) {
            ShowToast.showShortToast(getString(R.string.text_invite_right_phone_num));
            return;
        } else if (CommonUtils.isChinaPhoneLegal(mInvitefriend_phone_number) && !TextUtils.isEmpty(mInvitefriend_phone_number)) {
            // 网络请求接口获取验证码
            getNetCodeData(mInvitefriend_phone_number);
            //设置定时器防止多次请求获取验证码
            mTvInvitefriendCode.setEnabled(false);
            CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
                @Override
                public void onTick(long millis) {
                    mTvInvitefriendCode.setText("已发送" + (millis / 1000) + "s");
                    mTvInvitefriendCode.setBackgroundResource(R.drawable.shape_btn_code_nol);
                }

                @Override
                public void onFinish() {
                    mTvInvitefriendCode.setEnabled(true);
                    mTvInvitefriendCode.setText(getString(R.string.text_get_security_code));
                    mTvInvitefriendCode.setBackgroundResource(R.drawable.btn_invitefriend_shape);
                }
            }.start();
        } else {
            ShowToast.showShortToast(getString(R.string.text_please_set_right1_phone_num));
        }
        return;
    }

    /**
     * 获取网络信息请求验证码接口
     *
     * @param mMoblieNum
     */
    private void getNetCodeData(String mMoblieNum) {
        //请求网络
        OkHttpUtils.post().url(CommonAPI.URL_VERIFICATION_CODE)
                .addParams("mobile", mMoblieNum)//请求带上11位手机号码
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }

            @Override
            public void onResponse(String response) {
                KLog.e(response);
            }
        });
    }

    /**
     * 确定Sure
     */
    private void btnEnsure() {
        //获取手机号码
        mInvitefriend_phone_number = mEtInvitefriendNumber.getText().toString().trim();
        //获取验证码
        String invitefriend_verification = mEtInvitefriendVerification.getText().toString().trim();
        if (TextUtils.isEmpty(mInvitefriend_phone_number)) {
            ShowToast.showShortToast(getString(R.string.alert_please_input_phone_num));
        } else if (TextUtils.isEmpty(invitefriend_verification)) {
            ShowToast.showShortToast(getString(R.string.hint_input_qc_code));
        } else if (!(TextUtils.isEmpty(mInvitefriend_phone_number)) && (!TextUtils.isEmpty(invitefriend_verification))) {
            if (!CommonUtils.isChinaPhoneLegal(mInvitefriend_phone_number)) {
                ShowToast.showShortToast(getString(R.string.text_please_set_right_phone_num));
            } else {
                ensurePost(mInvitefriend_phone_number, invitefriend_verification);
            }
        }
    }

    /**
     *
     *
     * @param
     * @param invitefriend_phone_number
     * @param invitefriend_verification
     */
    private void ensurePost(String invitefriend_phone_number, String invitefriend_verification) {
        OkHttpUtils.post().url(URL_USERCREATE_RELATION)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("mobile", invitefriend_phone_number)
                .addParams("code", invitefriend_verification)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                KLog.e(response);
                SuccessEntity successEntity = GsonUtil.fromJson(response, SuccessEntity.class);
                //如果登录成功
                if (null != successEntity && successEntity.getStatus_code() == Integer.parseInt(CommonAPI.CONNECTION_STATUS_SUCCESS)) {
                    ShowToast.showShortToast(getString(R.string.text_invite_right));
                    mEtInvitefriendNumber.setText("");
                    mEtInvitefriendVerification.setText("");
                    //发消息
//                    Message message = new Message();
//                    message.what = 1;
//                    mHandler.sendMessage(message);
//                    mHandler.sendMessageDelayed(message, DELAY_TIME);
                }
//                mBtn_login.setEnabled(true);//可以点击按钮
            }

            @Override
            public void onError(Call request, Exception e) {
                // 完成请求失败的各种错误提示
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
//                mBtn_login.setEnabled(true);//可以点击按钮
            }
        });
    }

}